from sqlalchemy.orm import Session

import models
import schemas
import time




def get_user(db: Session, user_id: int):
    """
    根据 id 获取基本人员信息
    """
    return db.query(models.User).filter(models.User.id == user_id).first()


def get_user_by_name(db: Session, name: str):
    return db.query(models.User).filter(models.User.name == name).first()


def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()


def create_user(db: Session, user: schemas.UserCreate):
    print("sss", user.facevalue)
    db_user = models.User(name=user.name, phone=user.phone, roomnum=user.roomnum, imgbase64="", imgidx=0, facevalue=user.facevalue,
    remarks=user.remarks)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def get_enter_user(db: Session, enter_user_id: int):
    """
    根据 id 获取进入人员信息
    """
    return db.query(models.EnterUser).filter(models.EnterUser.id == enter_user_id).first()


def get_enter_user_by_name(db: Session, name: str):
    return db.query(models.EnterUser).filter(models.EnterUser.name == name).first()


def get_enter_user_by_phone(db: Session, phone: str):
    return db.query(models.EnterUser).filter(models.EnterUser.phone == phone).first()


def get_enter_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.EnterUser).offset(skip).limit(limit).all()


def create_enter_user(db: Session, user: schemas.EnterUserCreate):
    #获取当前时间
    enter_time = str(time.time())
    db_enter_user = models.EnterUser(name=user.name, phone=user.phone, roomnum=user.roomnum, entertime=enter_time,entertemp=user.entertemp,
    remarks=user.remarks, desc=user.desc)
    db.add(db_enter_user)
    db.commit()
    db.refresh(db_enter_user)
    return db_enter_user


def del_enter_user_by_name(db:Session, name: str):
    delete_user = db.query(models.EnterUser).filter(models.EnterUser.name == name).first()
    if delete_user:
        db.delete(delete_user)
        db.commit()
        return True
    else:
        return False

def edit_enter_user_by_name(db:Session, user: schemas.EnterUser):
    edit_user = db.query(models.EnterUser).filter(models.EnterUser.name == user.name).first()
    if edit_user:
        edit_user.name = user.name
        edit_user.phone = user.phone
        edit_user.roomnum = user.roomnum
        edit_user.entertemp = user.entertemp
        edit_user.remarks = user.remarks
        edit_user.desc = user.desc
        edit_user.entertime = user.entertime
        db.commit()
        db.refresh(edit_user)
        return True
    else:
        return False


    




# def get_items(db: Session, skip: int = 0, limit: int = 100):
#     return db.query(models.Item).offset(skip).limit(limit).all()


# def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
#     db_item = models.Item(**item.dict(), owner_id=user_id)
#     db.add(db_item)
#     db.commit()
#     db.refresh(db_item)
#     return db_item